﻿using System;
using System.Configuration;
using System.IO;
using System.Text;
using System.Threading;
using System.Xml;
using YEA.Infrastructure.Gateway;
using YEA.Utilities;
//TODO: integrate with exception manager

namespace MessageBusPublisher
{
    class Program 
    {
        static string mode;
        static IExceptionManager EM;
        static void Main(string[] args)
        {
            EM = new ExceptionManager();
            using (GatewayFactory gf = new YEA.Infrastructure.Gateway.GatewayFactory())
            {
                mode = ConfigurationManager.AppSettings["Mode"];
                mode = string.IsNullOrWhiteSpace(mode) ? "Transmitter" : mode;

                var mp = new MessageProcessor(EM);
                switch (mode.ToLower())
                {
                    default: 
                    case "Transmitter": Publish(gf);
                        break;
                    case "receiver": gf.GetAsyncReceiver("orderReceiver",mp.ConsumeMessage);
                        break;
                } 
            }
        }

        private static void Publish(GatewayFactory gf)
        {
            var mp = new MessageProcessor( EM);
            var publisher = gf.GetPublisher("orderPublisher",mp.ConvertObjectToMessage);
            var file = GetFile();
            while (!Console.KeyAvailable)
            {
                //Thread.Sleep( MessageProcessor.getSleepTime());
                publisher.Publish(file);
            }
        }

        static string GetFile()
        {
            var filename = ConfigurationManager.AppSettings["DummyFile"];
            var fileInfo = new FileInfo(filename);
            var file = string.Empty;
            using (var reader = fileInfo.OpenText())
            {
                file = reader.ReadToEnd();
            }
            return file;
        }

    }
    class MessageProcessor : YEA.Infrastructure.Gateway.Converter.StringToMessageConverter, IMessageConsumer
    {
        public IExceptionManager EM { get; set; }
        public MessageProcessor(IExceptionManager em)
        {
            EM = em;
        }
        public void ConsumeMessage(Message message, RabbitMQ.Client.IModel channel, DeliveryHeader header)
        {
            var sleeptime = getSleepTime();
            try
            {
                var messageText = ConvertFromMessageToString(message);
                //var xml = new XmlDocument();
                //xml.LoadXml(xmlstr);
                //Thread.Sleep(sleeptime);
                //Console.Write(messageText);
                channel.BasicAck(header.DeliveryTag, false);
                messageText = string.Empty;
            }
            catch (Exception ex)
            {
                EM.ManageException(ex);                
                channel.BasicReject(header.DeliveryTag, true);
            }
            
        }

       public static int getSleepTime()
       {
           try
           {
               return Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"]);
           }
           catch
           {
               return 1000;
           }
        }
        public override Message ConvertObjectToMessage(RabbitMQ.Client.IModel channel, object packetToSend)
        {
            var message = base.ConvertObjectToMessage(channel, packetToSend);
            message.RoutingKey = "order.uk.GAP";
            return message;
        }
        public string ConvertFromMessageToString(Message message)
        {
            var content = string.Empty;
            if (message.Properties.ContentType == YEA.Infrastructure.Gateway.Converter.StringToMessageConverter.PLAIN_TEXT)
            {
                var encoding = Encoding.GetEncoding(message.Properties.ContentEncoding ?? "utf-8");
                var ms = new MemoryStream(message.Body);
                var reader = new StreamReader(ms, encoding, false);
                content = reader.ReadToEnd();
            }
            return content;
        }
    }
}
